package models

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"hc_server/routers/response/agentResponse"
	"math"
	"time"
)

// AgentRate 代理商费率范围
type AgentRate struct {
	Model
	AgentId             int     `json:"agent_id" gorm:"comment:'代理商id'"`
	RateType            int     `json:"rate_type" gorm:"comment:'费率类型 0=D0 1=D1'"`
	Type                int     `json:"type" gorm:"default:0;comment:'是否编辑过 0=未编辑过 1=编辑过'"`
	WechatMin           float64 `json:"wechat_min" gorm:"type:decimal(10,6);comment:'微信费率最小值'"`
	WechatMax           float64 `json:"wechat_max" gorm:"type:decimal(10,6);comment:'微信费率最大值'"`
	AlipayMin           float64 `json:"alipay_min" gorm:"type:decimal(10,6);comment:'支付宝费率最小值'"`
	AlipayMax           float64 `json:"alipay_max" gorm:"type:decimal(10,6);comment:'支付宝费率最大值'"`
	YunPayLowMin        float64 `json:"yun_pay_low_min" gorm:"type:decimal(10,6);comment:'云闪付费率<=1000元 最小值'"`
	YunPayLowMax        float64 `json:"yun_pay_low_max" gorm:"type:decimal(10,6);comment:'云闪付费率<=1000元 最大值'"`
	YunPayHighMin       float64 `json:"yun_pay_high_min" gorm:"type:decimal(10,6);comment:'云闪付费率>1000元 最小值'"`
	YunPayHighMax       float64 `json:"yun_pay_high_max" gorm:"type:decimal(10,6);comment:'云闪付费率>1000元 最大值'"`
	DebitCardMin        float64 `json:"debit_card_min" gorm:"type:decimal(10,6);comment:'刷卡储蓄卡费率 最小值'"`
	DebitCardMax        float64 `json:"debit_card_max" gorm:"type:decimal(10,6);comment:'刷卡储蓄卡费率 最大值'"`
	DebitCardCappingMin float64 `json:"debit_card_capping_min" gorm:"type:decimal(10,6);comment:'刷卡储蓄卡封顶手续费 最小值'"`
	DebitCardCappingMax float64 `json:"debit_card_capping_max" gorm:"type:decimal(10,6);comment:'刷卡储蓄卡封顶手续费 最大值'"`
	CreditCardMin       float64 `json:"credit_card_min" gorm:"type:decimal(10,6);comment:'刷卡信用卡费率 最小值'"`
	CreditCardMax       float64 `json:"credit_card_max" gorm:"type:decimal(10,6);comment:'刷卡信用卡费率 最大值'"`
}

// AgentRateGetInfoByID 通过id获取详情
func AgentRateGetInfoByID(id interface{}) (interface{}, error) {
	agentRate := new(agentResponse.TeamManagerAgentRateInfoResponse)
	err := db.Model(&AgentRate{}).Where("id = ?", id).Scan(&agentRate).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Error("此代理费率获取失败: id:%d err:%v", id, err)
		return nil, fmt.Errorf("此代理费率获取失败")
	}
	if cast.ToInt(agentRate.Id) == 0 {
		return nil, errors.New("此代理费率获取失败")
	}

	return agentRate, nil
}

// AgentRateAddBaseRateInfo 添加代理基础费率信息
func AgentRateAddBaseRateInfo(agentId, superiorId interface{}) error {
	var rate AgentRate
	db.Model(&AgentRate{}).Where("agent_id = ?", superiorId).Scan(&rate)
	rate.AgentId = cast.ToInt(agentId)
	rate.CreatedAt = time.Now()
	rate.UpdatedAt = time.Now()
	rate.Type = 0
	rate.ID = 0

	err := db.Create(&rate).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("添加代理费率信息失败: rate:%v err:%v", rate, err)
		return fmt.Errorf("添加代理费率信息失败")
	}
	return nil
}

// AgentRateAddRateInfo 添加代理费率信息
func AgentRateAddRateInfo(rate AgentRate) error {
	err := db.Create(&rate).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("添加代理费率信息失败: rate:%v err:%v", rate, err)
		return fmt.Errorf("添加代理费率信息失败")
	}
	return nil
}

// AgentRateUpdateRateInfo 更新代理费率信息
func AgentRateUpdateRateInfo(mapd map[string]interface{}, id interface{}) error {
	mapd["type"] = 1
	err := db.Model(&AgentRate{}).Where("id = ?", id).Updates(mapd).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("更新代理费率信息失败: mapd:%v err:%v", mapd, err)
		return fmt.Errorf("更新代理费率信息失败")
	}
	return nil
}

// AgentRateGetRateInfo 获取代理费率信息
func AgentRateGetRateInfo(agentId interface{}) (interface{}, error) {
	var result = new(agentResponse.TeamManagerAgentRateGetRateInfoResponse)
	err := db.Model(&AgentRate{}).Where("agent_id = ?", agentId).Scan(&result).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("更新代理费率信息失败: agentId:%s err:%v", agentId, err)
		return nil, fmt.Errorf("更新代理费率信息失败")
	}
	return result, nil
}

// AgentRateGetRateInfoList 获取代理费率信息列表
func AgentRateGetRateInfoList(typed, agentId int, rate float32) (string, error) {
	var colName string
	switch typed {
	case 1:
		colName = "wechat_min"
	case 2:
		colName = "alipay_min"
	case 3:
		colName = "yun_pay_low_min"
	case 4:
		colName = "yun_pay_high_min"
	default:
		return "", errors.New("参数错误")
	}
	var result = make([]map[string]any, 0)
	err := db.Model(&AgentRate{}).Select("agent_id,"+colName+" AS rate").
		Where("FIND_IN_SET(agent_id,(?))", db.Model(&AgentRelation{}).Select("relation").Where("agent_id=?", agentId)).Scan(&result)
	if err.Error != nil {
		return "", err.Error
	}

	var recordMap map[string]any
	var newResult = make([]map[string]any, 0)
	for i, m := range result {
		if i > 0 {
			newResult = append(newResult, map[string]any{
				"agent_id": recordMap["agent_id"],
				"rate":     math.Round((cast.ToFloat64(m["rate"])-cast.ToFloat64(recordMap["rate"]))*100) / 100})
		}
		recordMap = m
	}

	newResult = append(newResult, map[string]any{
		"agent_id": recordMap["agent_id"],
		"rate":     math.Round((cast.ToFloat64(rate)-cast.ToFloat64(recordMap["rate"]))*100) / 100})

	res, _ := json.Marshal(newResult)
	return cast.ToString(res), nil
}
